<template>
  <div class="app-container container">
    <el-container>
      <el-aside width="220px" style="background-color: white;padding: 2px;margin-bottom: 0;">
        <!--组织结构数据-->
        <auth-project @selectBuilding="getCurrentProject" />
      </el-aside>
      <!--用户数据-->
      <el-main style="padding: 0 0 0 20px;">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="68px"
        >
          <el-form-item size="mini" label="">
            <el-input
              v-model.number="queryParams.floor"
              placeholder="请输入楼层"
              clearable
            />
          </el-form-item>
          <el-form-item size="mini" label="">
            <el-input
              v-model="queryParams.checkUserName"
              placeholder="请输入报验人"
              clearable
            />
          </el-form-item>
          <el-form-item size="mini" label="">
            <el-select v-model="queryParams.checktypeId" filterable clearable placeholder="请选择分项工程" @change="changeChecktype">
              <el-option
                v-for="item in checkTypeList"
                :key="item.fid"
                :label="item.fnumber + ' - ' +item.fnameL2"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item size="mini" label="">
            <el-select v-model="queryParams.checktableId" filterable clearable placeholder="请选择工序" style="width: 300px;">
              <el-option
                v-for="item in checkTableList"
                :key="item.fid"
                :label="item.cfseq + ' - ' + item.fnameL2"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item size="mini" label="">
            <el-select v-model="queryParams.state" filterable placeholder="状态" clearable>
              <el-option
                v-for="item in checkStatus"
                :key="'checkResult' + item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item size="mini" label="">
            <el-date-picker
              v-model="queryParams.beginDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="报验时间从"
            />
          </el-form-item>
          <el-form-item size="mini" label="">
            <el-date-picker
              v-model="queryParams.endDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="报验时间到"
            />
          </el-form-item>
          <el-form-item size="mini">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-view" type="info" size="mini" @click="openCancelWd">撤销报验列表</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" size="mini" :data="data" height="calc(100vh - 280px)">
          <el-table-column label="状态" align="center" prop="cfstate" min-width="8%">
            <template slot-scope="scope">
              {{ scope.row.state == 2 ? '已报验' : '未报验' }}
            </template>
          </el-table-column>
          <el-table-column label="分项工程" align="center" prop="checkTypeName" min-width="12%" />
          <el-table-column label="工序" align="center" prop="checkTableName" min-width="13%" />
          <el-table-column label="检验批" align="center" prop="batchNumber" min-width="7%" />
          <el-table-column label="检验批说明" align="center" prop="description" min-width="23%" />
          <el-table-column label="报验人" align="center" prop="inspector" min-width="7%" />
          <el-table-column label="报验时间" align="center" prop="inspectionTime" min-width="10%" />
          <el-table-column label="操作时间" align="center" min-width="10%">
            <template slot-scope="scope">
              {{ scope.row.createTime | dateFilter }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="10%">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
              >详情
              </el-button>
              <el-button
                v-hasPermi="['qualityManage:Inspection:cancel']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleCancelCheck(scope.row)"
              >撤销报验
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 撤销报验对话框 -->
        <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="撤销原因" prop="cancelReasonId">
              <el-select v-model="form.cancelReasonId" placeholder="请选择" style="width: 380px;">
                <el-option
                  v-for="item in specialTypes"
                  :key="item.fid"
                  :label="item.fnameL2"
                  :value="item.fid"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :loading="cancelLoading" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-main>
    </el-container>

    <!-- 报验详情 -->
    <el-dialog :title="form2.title" :visible.sync="openView" :close-on-click-modal="false" width="800px" custom-class="detail-container">
      <template slot="title">
        <span style="font-size: 20px ;font-weight: bold; color: #606266">{{ form2.title }}</span>
      </template>
      <div v-loading="detailLoading" class="process-check">
        <el-card class="check-condition">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="line" style="text-align:center">
                    <span>工序名称：</span><span style="text-align:center">{{ form2.info.checkTableName }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="line">
                    <span>报验批次：</span><span>第 {{ form2.info.batchNumber }} 批次</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="line">
                    <span>报验人员：</span><span>{{ form2.info.inspector }}</span>
                  </div>
                </el-col>
                <el-col :span="form2.info.unitType === 6 ? 8 : 16">
                  <div class="line">
                    <span>报验日期：</span><span>{{ form2.info.inspectionTime }}</span>
                  </div>
                </el-col>
                <el-col v-if="form2.info.unitType === 6" :span="8">
                  <div class="line">
                    <span>完成率：</span><span>{{ form2.info.percent + '%' }}</span>
                  </div>
                </el-col>
                <el-col v-if="form2.info.unitType != 3 && form2.info.unitType != 7" :span="8">
                  <div class="line">
                    <span>报验范围：</span>
                    <span v-if="form2.info.unitType === 2 && form2.info.spaceType === 1" style="text-align:center"><a href="javascript:void(0);" @click="getInspectArea">点击查看</a></span>
                    <span v-else-if="form2.info.unitType === 4 || form2.info.unitType === 5" style="text-align:center"><a href="javascript:void(0);" @click="getBeInspect">点击查看</a></span>
                    <span v-else-if="form2.info.unitType === 6" style="text-align:center">{{ directionMap[form2.info.direction] }}</span>
                    <span v-else style="text-align:center">{{ form2.info.startFloor }}层 - {{ form2.info.endFloor }}层</span>
                  </div>
                </el-col>
                <el-col :span="24">
                  <div class="line">
                    <span>批次说明：</span><span>{{ form2.info.description }}</span>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="24">
              <div class="line">
                <span class="check-title">验收要点：</span>
              </div>
              <template>
                <el-table
                  :data="form2.points"
                >
                  <el-table-column type="index" />
                  <el-table-column
                    prop="content"
                    label="验收要点"
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.key== 1" style="color: red">{{ scope.row.content }}</span>
                      <span v-else>{{ scope.row.content }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="key"
                    label="强制要求"
                    width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.key== 1" style="color: red">是</span>
                      <span v-else>否</span>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-col>
          </el-row>
        </el-card>

        <el-card style="margin-top: 10px">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="order-detail-data">
                <span style="color: #99a9bf"> 标准做法：</span>
                <!--<span><img style="height:200px" :src="feedbackForm.attachment" /></span>-->
                <span v-if="form2.info.tableFileIds && form2.info.tableFileIds.length>0">
                  <el-image
                    v-for="url in filesTableUrl"
                    :key="url"
                    class="image-size"
                    fit="contain"
                    :src="url"
                    :preview-src-list="filesTableUrl"
                  />
                </span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="order-detail-data">
                <span style="color: #99a9bf"> 附件：</span>
                <!--<span><img style="height:200px" :src="feedbackForm.attachment" /></span>-->
                <span v-if="form2.info.fileIds.length>0">
                  <el-image
                    v-for="url in filesUrl"
                    :key="url"
                    class="image-size"
                    fit="contain"
                    :src="url"
                    :preview-src-list="filesUrl"
                  />
                </span>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-dialog>
    <!-- 查看报验平面图 -->
    <el-dialog title="报验情况" :visible.sync="inspectStateDialog">
      <div style="max-height: 600px;overflow: auto">
        <check-state-area :building-id="form2.info.buildingId" :check-table-id="form2.info.checkTableId" :sel-room-ids="selRoomIds" show-type="inspect" :is-edit="false" />
      </div>
    </el-dialog>
    <!-- 桩基 -->
    <el-dialog title="桩基情况" width="500px" :visible.sync="pileState.visible">
      <div style="max-height: 600px;overflow: auto">
        <el-table v-loading="pileState.loading" size="mini" :data="pileState.data">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="桩基编号" prop="pileName" />
        </el-table>
      </div>
    </el-dialog>
    <!-- 公区 -->
    <el-dialog title="公区情况" width="550px" :visible.sync="publicState.visible">
      <line-draw-plane ref="drawPlane" :file-id="publicState.fileId" :line-arr="publicState.lineArr" />
    </el-dialog>
    <!-- 撤销报验列表 -->
    <el-dialog title="撤销报验情况" width="1100px" :visible.sync="cancelState.visible">
      <el-table v-loading="cancelState.loading" size="mini" :data="cancelState.data" height="calc(100vh - 280px)">
        <!--        <el-table-column label="状态" align="center" prop="cfstate" min-width="80">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ scope.row.state == 2 ? '已报验' : '未报验' }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="分项工程" prop="checkTypeName" min-width="110" />
        <el-table-column label="工序" prop="checkTableName" min-width="110" />
        <el-table-column label="检验批" align="center" prop="batchNumber" min-width="60" />
        <el-table-column label="检验批说明" prop="description" min-width="150" />
        <el-table-column label="报验人" prop="inspector" min-width="80" />
        <el-table-column label="报验时间" align="center" prop="inspectionTime" min-width="140" />
        <el-table-column label="撤销人" prop="creatorName" min-width="80" />
        <el-table-column label="撤销时间" align="center" min-width="140">
          <template slot-scope="scope">
            <el-tag type="danger">{{ scope.row.cancelTime }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document-copy"
              v-hasPermi="['cqCheck:inspection:recover']"
              @click="handleRecover(scope.row,scope.index)"
            >恢复报验
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="cancelState.total > 0"
        :total="cancelState.total"
        :page.sync="cancelState.pageNum"
        :limit.sync="cancelState.pageSize"
        @pagination="getCancelList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { checkResultData } from '@/utils/baseData'
import { list, getRecord, revocation, listCancelReason, getInspectionRoom, getInspectionPublic, getInspectionPile, getCancelInspectList, recoverInspection } from '@/api/qualityManage/inspection'
import AuthProject from './components/AuthProject'
import { listCheckType } from '@/api/qualityManage/checkType'
import { listCheckTable } from '@/api/qualityManage/checkTable'
import CheckStateArea from '../components/CheckStateArea'
import LineDrawPlane from './components/LineDrawPlane'

let specialTypes = []
export default {
  name: 'CheckRecord',
  filters: {
    specialType(id) {
      for (let i = 0; i < specialTypes.length; i++) {
        if (specialTypes[i].fid === id) {
          return specialTypes[i].fnameL2
        }
      }
      return id
    }
  },
  components: {
    CheckStateArea,
    AuthProject,
    LineDrawPlane
  },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      checkTableList: [],
      // 弹出层标题
      title: '',
      title2: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        buildingId: '',
        floor: '',
        roomName: '',
        checkUserName: '',
        checktypeId: '',
        checktableId: '',
        chkResult: '',
        beginDate: '',
        endDate: ''
      },
      data: [],
      loading: false,
      printObj: {},
      printConfig: {
        id: 'print',
        popTitle: '查看整改通知单-工程协同管理',
        callback: () => {
          this.printBtnLoading = false
        }
      },
      form: {},
      form2: { info: { fileIds: [], tableFileIds: [] }, title: '', points: [] },
      // 表单校验
      rules: {
        cancelReasonId: [
          { required: true, message: '请选择取消原因', trigger: 'change' }
        ]
      },
      checkStatus: [
        { label: '已报验', value: 2 },
        { label: '未报验', value: 1 }],
      detailInfo: {},
      detailPoints: [],
      cancelCheckParam: {},
      printObjLoading: false,
      printBtnLoading: false,
      currentBuilding: {},
      open: false,
      openView: false,
      checkResultData: checkResultData,
      checkTypeList: [],
      specialTypes: [],
      filesUrl: [],
      filesTableUrl: [],
      cancelLoading: false,
      /* 报验详情的房间列表 */
      inspectRoomData: [],
      /* 报验详情平面图 */
      inspectStateDialog: false,
      /* 当前报验的房屋IDS */
      selRoomIds: [],
      detailLoading: false,
      /* 桩基情况 */
      pileState: {
        visible: false,
        data: [],
        loading: false
      },
      /* 公区数据 */
      publicState: {
        visible: false,
        fileId: null,
        lineArr: []
      },
      /* 撤销报验列表 */
      cancelState: {
        visible: false,
        loading: false,
        data: [],
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      directionMap: { 'e': '东面', 's': '南面', 'w': '西面', 'n': '北面' }
    }
  },
  watch: {},
  created() {
    this.getCheckList()
    this.getCheckTableList()
  },
  methods: {
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.inspectionId !== undefined) {
            this.cancelLoading = true
            revocation(this.form).then(response => {
              this.cancelLoading = false
              if (response.code === 200) {
                this.msgSuccess('操作成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancel2() {
      this.openView = false
      this.reset()
    },
    mounted() { // 初始化
      if (this.form2.info.fileIds) {
        this.filesUrl = this.form2.info.fileIds.split(',').map(id => process.env.VUE_APP_BASE_API + '/file/download?fileKey=' + id)
      }
    },
    getCheckList() { // 分部分项
      listCheckType({}).then(response => {
        this.checkTypeList = response.data
      })
      listCancelReason({}).then(response => {
        this.specialTypes = response.data
        specialTypes = response.data
      })
    },
    changeChecktype() {
      this.queryParams.checktableId = ''
      this.getCheckTableList()
    },
    getCheckTableList() { // 获取工序列表
      listCheckTable({ 'cfchecktypeid': this.queryParams.checktypeId }).then(
        (response) => {
          this.checkTableList = response.data
        }
      ).catch(() => {
      })
    },
    getCurrentProject(data) {
      if (data.id) {
        this.queryParams.buildingId = data.id
        this.getList()
      } else {
        this.data = []
      }
      this.currentBuilding = data
    },
    /** 查询分部分项列表 */
    getList() {
      if (!this.queryParams.buildingId) {
        return this.$message.warning('请先选择楼栋')
      }
      this.loading = true
      list(this.queryParams).then(response => {
        this.data = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        buildingId: this.currentBuilding.id
      }
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        inspectionId: undefined,
        cancelReasonId: undefined,
        fnameL2: undefined
      }
      this.resetForm('form')
    },
    /** 撤销报验按钮操作 */
    handleCancelCheck(row) {
      this.reset()
      this.form = { 'inspectionId': row.id }
      this.open = true
      this.title = '撤销报验'
    },
    /* 获取详情 */
    handleDetail(row) {
      this.openView = true
      if (this.detailLoading) {
        return
      }
      this.detailLoading = true
      getRecord({ id: row.id }).then(response => {
        this.detailInfo = response.data.info
        this.detailPoints = response.data.points
        this.form2 = response.data
        if (this.form2.info.fileIds && this.form2.info.fileIds.length) {
          this.filesUrl = this.form2.info.fileIds.toString().split(',').map(id => process.env.VUE_APP_BASE_API + '/file/download?fileKey=' + id)
          console.log(this.filesUrl)
        }
        if (this.form2.info.tableFileIds) {
          this.filesTableUrl = this.form2.info.tableFileIds.toString().split(',').map(id => process.env.VUE_APP_BASE_API + '/file/download?fileKey=' + id)
          console.log(this.filesTableUrl)
        }
      }).finally(() => {
        this.detailLoading = false
      })
    },
    /* 查看报验范围 */
    getInspectArea() {
      this.selRoomIds = []
      getInspectionRoom({ fid: this.detailInfo.id }).then(response => {
        this.inspectRoomData = response.data
        for (var room of response.data) {
          this.selRoomIds.push(room.fid)
        }
        this.inspectStateDialog = true
      })
    },
    /* 查询房屋列表 */
    handleRoomQuery(val) {
      this.inspectRoomGridData = this.inspectRoomData.filter(item => item.fnameL2 && item.fnameL2.indexOf(val) !== -1)
    },
    /* 如果是桩基或者公区 则特殊展示 */
    getBeInspect() {
      // 桩基
      if (this.form2.info.unitType === 4) {
        getInspectionPile({ fid: this.detailInfo.id }).then((response) => {
          if (response.code === 200) {
            this.pileState.data = response.data
            this.pileState.visible = true
          }
        }).catch()
      } else if (this.form2.info.unitType === 5) {
        // 公区
        getInspectionPublic({ fid: this.detailInfo.id }).then((response) => {
          if (response.code === 200) {
            const drawData = response.data[0]
            this.publicState.fileId = drawData.fileId
            this.publicState.lineArr = [{ status: -1, points: JSON.parse(drawData.drawArea) }]
            this.publicState.visible = true
            this.$nextTick(() => {
              this.$refs.drawPlane.init()
            })
          }
        }).catch()
      }
    },
    openCancelWd() {
      this.cancelState.visible = true
      this.cancelState.pageNum = 1
      this.getCancelList()
    },
    /* 获取撤销报验列表 */
    getCancelList() {
      getCancelInspectList({
        buildingId: this.currentBuilding.id,
        pageNum: this.cancelState.pageNum,
        pageSize: this.cancelState.pageSize }).then((response) => {
        if (response.code === 200) {
          this.cancelState.data = response.rows
          this.cancelState.visible = true
          this.cancelState.total = response.total
        }
      }).catch()
    },
    /** 撤销报验按钮操作 */
    async handleRecover(row) {
      const inspectionId = row.id
      const self = this
      this.$confirm(
        `是否要恢复当前报验?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(await function() {
          self.cancelState.loading = true
          recoverInspection({inspectionId}).then((response) => {
            if (response.code === 200) {
              self.getCancelList()
              self.msgSuccess('操作成功')
              self.cancelState.loading = false
            }
          }).catch(function () {
            self.cancelState.loading = false
          })
        })
        .catch(function() {
          self.cancelState.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.print-wrap {
  height: 80vh;
  overflow: auto;
  position: relative;

  .print-btn {
    position: absolute;
    right: 20px;
  }
}

.container {
  height: calc(100vh - 100px);
  overflow-y: hidden;
}
</style>
<style scoped lang="scss">
/deep/ .el-dialog__body {
  padding-top: 0;
}
.order-detail-data {
  display: flex;
  line-height: 24px;
  margin-top: 10px;

  span:nth-child(1) {
    white-space: nowrap;
    color: #606266;
  }

  .textarea-disable {
    width: 75%;
  }

  .image-size {
    width: 100px;
    height: 100px;
    margin: 0 10px 10px 0;

    /deep/ .el-icon-circle-close {
      background-image: linear-gradient(to right, #2ce6c9, #00baff);
      -webkit-background-clip: text;
      color: transparent;
    }
  }
}

.label {
  color: #99a9bf;
}

.primary {
  color: #409EFF;
}

.danger {
  color: #F56C6C;
}
.detail-container {
  padding: 10px 20px;
}
.process-check {

  .check-condition {
    color: #606266;

    .check-title {
      font-weight: bold;
    }

    .line {
      padding: 10px 0;
      border-bottom: 1px solid #e6ebf5;
      display: flex;

      span:nth-child(1) {
        width: 70px;
        text-align: right;
        white-space: nowrap;
        color: #99a9bf;
      }

      .image-size {
        width: 100px;
        height: 100px;
        margin: 0 10px 10px 0;
      }

      .unqualified {
        display: flex;

        span:nth-child(1) {
          white-space: nowrap;
          margin-right: 20px;
        }
      }

      .qualified {
        display: flex;

        span:nth-child(1) {
          white-space: nowrap;
          margin-right: 20px;
        }
      }

      .deadline {
        color: #F56C6C;
        display: inline-block;
        margin-right: 200px;
      }

      .quality {
        display: inline-block;
      }
    }
  }
}
</style>
